<?php

namespace app\admin\service;

use bxkj_common\service\Sevrice;

class AuthRule extends Sevrice
{
    public function getList(array $get = [], $sort = '', $field = '*')
    {
        $list = $this->where($get)->field($field)->select();
        return $list ?? [];
    }

    public function getOne(array $get = [])
    {
        $one = $this->where($get)->find();
        return $one ?? [];
    }

    public function add($params): bool
    {
        $validate = new \app\admin\validate\AuthRule();
        $result = $validate->check($params);
        if (!$result) return $this->setError($validate->getError());
        $id = $this->save($params);
        if (!$id) return $this->setError(lang('ADD_FAIL'));
        return true;
    }

    public function edit($params): bool
    {
        $validate = new \app\admin\validate\AuthRule();
        $result = $validate->check($params);
        if (!$result) return $this->setError($validate->getError());
        $id = $this->update($params);
        if (!$id) return $this->setError(lang('EDIT_SUCCESS'));
        return true;
    }

    public function del($ids): bool
    {
        $ids = array_unique(is_array($ids) ? $ids : explode(',', $ids));
        $authList = $this->getList([], '', 'id,pid');
        if (empty($authList)) return false;
        $authList = $authList->toArray();
        foreach ($ids as $id) {
            $tmp = [];
            $result = $this->getChildren((int)$id, $authList);
            $tmp = array_column($result, 'id');
            $ids = array_merge($ids, $tmp);
        }
        $ids = array_unique($ids);
        $num = $this->whereIn('id', $ids)->delete();
        if (!$num) return $this->setError(lang('DELETE_FAIL'));
        return true;
    }

    public function getChildren(int $pid, $data)
    {
        $treeList = [];
        foreach ($data as $v) {
            if ($pid == $v['pid']) {
                $node = $v;
                $child = $this->getChildren($v['id'], $data);
                if (!empty($child)) {
                    $node['child'] = $child;
                }
                $treeList[] = $node;
            }
        }
        return $treeList;
    }
}